package com.music.ui.activity;

import android.os.Bundle;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.music.R;
import com.music.ui.adapter.SearchHistoryAdapter;
import com.music.ui.adapter.SearchSongAdapter;
import com.music.entity.MusicInfo;
import com.music.entity.SearchHistory;
import com.music.entity.online.SearchMusic;
import com.music.entity.online.SongPlay;
import com.music.loader.Api;
import com.music.loader.DataRequest;
import com.music.service.MusicUtil;
import com.music.sqlite.DBUtil;
import com.music.utils.StringUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by dingfeng on 2016/9/30.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout back;
    private EditText etSearch;
    private ImageView cancel;
    private RelativeLayout btSearch;
    private LinearLayout ll_history;
    private LinearLayout ll_result;
    private ListView historyListView;
    private ListView searchListView;

    private TextView history_emptyView;
    private TextView search_emptyView;
    private View footer;
    private Button btFooter;

    private List<SearchHistory> mHistoryList = new ArrayList<>();
    private SearchHistoryAdapter mSearchHistoryAdapter;

    private List<SearchMusic.SearchSong> mSongList = new ArrayList<>();
    private SearchSongAdapter mSearchSongAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        getHistoryData();
    }

    private void initView() {
        back = (RelativeLayout) findViewById(R.id.back);
        back.setOnClickListener(this);
        etSearch = (EditText) findViewById(R.id.etSearch);
        btSearch = (RelativeLayout) findViewById(R.id.btSearch);
        btSearch.setOnClickListener(this);
        cancel = (ImageView) findViewById(R.id.cancel);
        cancel.setOnClickListener(this);
        ll_history = (LinearLayout) findViewById(R.id.ll_history);
        ll_result = (LinearLayout) findViewById(R.id.ll_result);
        ll_result.setVisibility(View.GONE);

        historyListView = (ListView) findViewById(R.id.historyListView);
        searchListView = (ListView) findViewById(R.id.searchListView);
        history_emptyView = (TextView) ll_history.findViewById(R.id.emptyView);
        historyListView.setEmptyView(history_emptyView);
        search_emptyView = (TextView) ll_result.findViewById(R.id.emptyView);
        searchListView.setEmptyView(search_emptyView);
        footer = LayoutInflater.from(this).inflate(R.layout.include_footer_button, null);
        btFooter = (Button) footer.findViewById(R.id.btFooter);
        btFooter.setText("清除历史记录");
        btFooter.setOnClickListener(this);
        historyListView.addFooterView(footer);

        historyListView.setOnItemClickListener(historyItemClick);
        searchListView.setOnItemClickListener(searchItemClick);

        mSearchHistoryAdapter = new SearchHistoryAdapter(this, mHistoryList);
        historyListView.setAdapter(mSearchHistoryAdapter);
        mSearchSongAdapter = new SearchSongAdapter(this, mSongList);
        searchListView.setAdapter(mSearchSongAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                onBackPressed();
                break;
            case R.id.btSearch:
                if (etSearch.getText() != null) {
                    String keyword = etSearch.getText().toString();
                    if (!StringUtil.isEmpty(keyword)) {
                        onSearch(keyword);
                    }
                }
                break;
            case R.id.cancel:
                etSearch.setText("");
                ll_history.setVisibility(View.VISIBLE);
                ll_result.setVisibility(View.GONE);
                break;
            case R.id.btFooter:
                DBUtil.getInstance().getSearchDao().deleteAll();
                mHistoryList.clear();
                mSearchHistoryAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

    AdapterView.OnItemClickListener historyItemClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String keyword = mHistoryList.get(position).getKeyword();
            if (!StringUtil.isEmpty(keyword)) {
                etSearch.setText(keyword);
                onSearch(keyword);
            }
        }
    };

    AdapterView.OnItemClickListener searchItemClick = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SearchMusic.SearchSong song = mSongList.get(position);
            playOnline(song);
        }
    };

    private void getHistoryData() {
        List<SearchHistory> list = DBUtil.getInstance().getSearchDao().queryAll(0, 20, "ctime", false);
        if (list != null) {
            mHistoryList.clear();
            mHistoryList.addAll(list);
            mSearchHistoryAdapter.notifyDataSetChanged();
        }
    }

    private void onSearch(String keyword) {
        showLoadingProgressDialog();
        ll_history.setVisibility(View.GONE);
        ll_result.setVisibility(View.VISIBLE);
        // save to db
        SearchHistory search = new SearchHistory();
        search.setKeyword(keyword);
        search.setCtime(Calendar.getInstance().getTimeInMillis());
        DBUtil.getInstance().getSearchDao().insertOrUpdate(search);
        // reset data
        getHistoryData();

        doSearch(keyword);
    }

    private void doSearch(String keyword) {
        DataRequest.getInstance().getSearchResult(keyword, new DataRequest.Callback<List<SearchMusic.SearchSong>>() {
            @Override
            public void onSuccess(List<SearchMusic.SearchSong> data) {
                if (data != null) {
                    mSongList.clear();
                    mSongList.addAll(data);
                    mSearchSongAdapter.notifyDataSetChanged();

                }
                closeLoadingProgressDialog();
            }

            @Override
            public void onError(String err) {
                closeLoadingProgressDialog();
            }
        });
    }

    private void playOnline(final SearchMusic.SearchSong song) {
        DataRequest.getInstance().getOnlineUri(Api.METHOD_DOWNLOAD_MUSIC,
                song.getSongId(), new DataRequest.Callback<SongPlay>() {
                    @Override
                    public void onSuccess(SongPlay data) {
                        if (data != null && data.getBitrate() != null) {
                            SongPlay.Bitrate bitrate = data.getBitrate();
                            final MusicInfo music = new MusicInfo();
                            music.setMusicName(song.getSongName());
                            music.setArtist(song.getArtistName());
                            music.setData(bitrate.getFilelink());
                            music.setDuration(bitrate.getFileDuration() * 1000);
                            try {
                                MusicUtil.sService.playOnline(music);
                            } catch (RemoteException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(String err) {

                    }
                });
    }

}
